package system

import (
	"bytes"
	"encoding/csv"
	"encoding/json"
	"mytest/models"
	"mytest/models/request"
	"strings"

	"gorm.io/gorm"
)

func DownCsv(db *gorm.DB, f request.DownByField) ([]byte, error) {
	var selects string
	for k, v := range f.Fields {
		selects += v
		if k != len(f.Fields)-1 {
			selects += ","
		}
	}
	var res []map[string]interface{}
	err := db.Model(&models.Student{}).Select(selects).Find(&res).Error
	if err != nil {
		return nil, err
	}
	out := bytes.Buffer{}
	newCsv := csv.NewWriter(&out)
	//先装头
	_ = newCsv.Write(f.Fields)
	Field := make([]string, 0)
	for _, stu := range res {
		for _, v := range f.Fields {
			cell, _ := json.Marshal(stu[v])
			tmp := string(cell)
			tmp = strings.ReplaceAll(tmp, "\"", "")
			Field = append(Field, tmp)
		}
		_ = newCsv.Write(Field)
		Field = []string{}
	}
	newCsv.Flush()
	return out.Bytes(), nil
}
